import type { ComponentStyleIdType } from '../../types/interfaces'
import type { ToggleSwitchProps } from './types'
import { UIComponent } from '../../lib/abstract'
import { ComponentStyleId } from '../../types/constants'
import { styles } from './styles'
import { DEFAULT_TOGGLE_PROPS } from './types'

/**
 * 开关切换组件
 * @param id - 开关唯一ID
 * @param checked - 是否选中状态
 * @param immediateEffect - 是否立即生效
 * @param onChange - 状态变化回调
 */
export class ToggleSwitch extends UIComponent<ToggleSwitchProps> {
  id: string = 'toggle-switch'
  readonly description: string = '开关切换组件'
  readonly styleId: string = ComponentStyleId[this.name]
  element: JQuery<HTMLElement> | undefined = undefined

  get name(): ComponentStyleIdType {
    return 'ToggleSwitch'
  }

  get className(): string {
    return 'toggle-switch'
  }

  constructor(props: ToggleSwitchProps) {
    super({ // 合并默认配置和传入的 props
      ...DEFAULT_TOGGLE_PROPS,
      ...props,
    })

    // 注册样式
    this.registerStyles()
  }

  ELEMENT_SELECTORS = {
    input: { selector: `#${this.props.id}`, dynamic: false, unique: true },
  }

  render(): string {
    const { id, checked, disabled, labelOn, labelOff, effectType } = this.props

    return `
      <label class="toggle-switch" data-effect="${effectType}">
        <input id="${id}" type="checkbox" ${checked ? 'checked' : ''} ${disabled ? 'disabled' : ''}>
        <span class="slider"></span>
        <span class="toggle-label">${checked ? `${labelOn}` : `${labelOff}`}</span>
      </label>
    `
  }

  bindEvents(): void {
    const $input = this.getElement('input')
    if (this.props.onChange) {
      $input?.on('change', () => {
        this.props.onChange?.($input.prop('checked'))
      })
    }
  }

  getStyles(): string {
    return styles()
  }

  reset(): void {
  }
}
